#include "shell_login.h"

#define DEFAULT_PASSWORD "123456"

void login_init(void)
{
	//printk("Shell Login Demo\nHint: password = %s\n", DEFAULT_PASSWORD);
	shell_set_root_cmd("login");
}

static int check_passwd(char *passwd)
{
	/* example only -- not recommended for production use */
	printk("PASSWD:%s",passwd);
	return strcmp(passwd, DEFAULT_PASSWORD);
}

int cmd_login(const struct shell *shell, size_t argc, char **argv)
{
	static uint32_t attempts;
	
	if (check_passwd(argv[1]) != 0) {
		shell_error(shell, "Incorrect password!");
		attempts++;
		if (attempts > 3) {
			k_sleep(K_SECONDS(attempts));
		}
		return -EINVAL;
	}

	/* clear history so password not visible there */
	z_shell_history_purge(shell->history);
	shell_obscure_set(shell, false);
	shell_set_root_cmd(NULL);
	shell_prompt_change(shell, "uart:~$ ");
	shell_print(shell, "Shell Login Demo\n");
	shell_print(shell, "Hit tab for help.\n");
	attempts = 0;
	return 0;
}

int cmd_logout(const struct shell *shell, size_t argc, char **argv)
{
	shell_set_root_cmd("login");
	shell_obscure_set(shell, true);
	shell_prompt_change(shell, "login: ");
	shell_print(shell, "\n");
	return 0;
}

SHELL_COND_CMD_ARG_REGISTER(CONFIG_SHELL_START_OBSCURED, login, NULL,
			    "<password>", cmd_login, 2, 0);

SHELL_COND_CMD_REGISTER(CONFIG_SHELL_START_OBSCURED, logout, NULL,
			"Log out.", cmd_logout);